<template>
  <div class="form-card">
    <el-form :model="form" label-width="100px" class="form-body">
      <el-row>
        <el-col :span="12">
          <el-form-item label="素材名称">
            <el-input v-model="form.templateTitle" placeholder="请输入素材名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="分类选择">
            <el-cascader
                v-model="selectedCategories"
                :options="categoryOptions"
                :props="{ checkStrictly: false }"
                placeholder="请选择分类"
                clearable
                style="width: 100%"
                @change="handleCategoryChange"
            />
          </el-form-item>

        </el-col>

        <el-col :span="12">
          <el-form-item label="软件">
            <el-input v-model="form.software" placeholder="请输入软件" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="格式">
            <el-input v-model="form.format" placeholder="如 ppt, docx" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="比例">
            <el-input v-model="form.proportion" placeholder="如 16:9" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="大小 (MB)">
            <el-input-number v-model="form.size" :min="0" :step="0.1" style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="页数">
            <el-input-number v-model="form.pages" :min="0" style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="展示顺序">
            <el-input-number v-model="form.viewOrder" :min="1" style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="Agent ID">
            <el-select v-model="form.agentId" clearable>
              <el-option v-for="item in AgentData"  placeholder="请选择Agent" :label="item.title" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="限制">
            <el-input v-model="form.limitation" placeholder="如 商用/仅限个人" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="版权说明">
            <el-input v-model="form.copyrightNotice" placeholder="版权信息" />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="素材内容">
<!--            <Editor-->
<!--                v-model="form.templateContent"-->
<!--                :default-config="editorConfig"-->

<!--                :mode="'default'"-->
<!--                style="border: 1px solid #ccc; height: 400px;"-->
<!--            />-->
           <div>
             <QuillEditor
                 v-model:content="form.templateContent"
                 content-type="html"
                 toolbar="full"
                 theme="snow"
                 @ready="onEditorReady"
             />
           </div>
<!--            <el-input v-model="form.templateContent" placeholder="请输入素材内容" />-->
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="素材简介">
            <el-input v-model="form.templateIntroduce" placeholder="请输入素材简介" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="封面图">
            <uploadimg v-model="form.coverUrl"/>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="模板地址">
            <excel v-model="form.templateUrl"/>
          </el-form-item>
        </el-col>

      </el-row>


      <el-form-item style="text-align: center; margin-top: 30px">
        <el-button type="primary" @click="submitForm">提交</el-button>
<!--        <el-button @click="resetForm">重置</el-button>-->
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import {getassetList, templateupdate, uploadfile} from "../../apis/asset/index.js";
import Excel from "../../components/uploadimg/excel.vue";
import {getList} from "../../apis/agent.js";
import {ElMessage} from "element-plus";
import {useUserStore} from "../../stores/user.js";
import pinia from "../../stores/store.js";
import axios from "axios";
import {QuillEditor} from "@vueup/vue-quill";
import Exit from "../../components/uploadimg/Exit.vue";

// 表单数据
const form = ref({
  templateIntroduce:"",
  coverUrl:"",
  templateUrl:"",
  templateTitle: '',
  categoryId1: 0,
  categoryId2: 0,
  categoryId3: 0,
  agentId: null,
  software: '',
  format: '',
  size: 0,
  pages: 0,
  proportion: '',
  limitation: '',
  copyrightNotice: '',
  viewOrder: 1,
  createTime: '',
  templateContent:""
})

const rawCategoryList = ref([])
const AgentData = ref([])
const props = defineProps({
  mediaDigData: Object
})
onMounted( () => {
  getLists()


})
const uploadHeaders=ref( ``)
const store = useUserStore(pinia)

// 编辑器配置

const onEditorReady = (quill) => {
  // 自定义图片上传逻辑
  const toolbar = quill.getModule('toolbar')
  toolbar.addHandler('image', () => {
    selectLocalImage(quill)
  })
}

function selectLocalImage(quill) {
  const input = document.createElement('input')
  input.setAttribute('type', 'file')
  input.setAttribute('accept', 'image/*')
  input.click()

  input.onchange = async () => {
    const file = input.files[0]
    if (file) {
      // 上传到服务器
      const formData = new FormData()
      formData.append('file', file)

      try {
        uploadfile(formData).then(res=>{
          console.log(JSON.stringify(res))
          const imageUrl = res.url // 假设返回的是 { url: 'http://yourdomain.com/img.jpg' }

          const range = quill.getSelection()
          quill.insertEmbed(range.index, 'image', imageUrl)
        })

      } catch (e) {
        console.error('上传失败', e)
      }
    }
  }
}


const getLists =  () => {
   getassetList().then(res=>{

     rawCategoryList.value = res
     categoryOptions.value=convertTree(rawCategoryList.value)

     getListAgent()
   })
}
const getListAgent =  () => {
  getList({pageNum:1,pageSize:1000}).then(res=>{
    AgentData.value=res.list
    if(Object.keys(props.mediaDigData).length>0){
      let newData=props.mediaDigData
      if(newData.templateContent===null){
        newData.templateContent=""
      }
      form.value=newData
      selectedCategories.value=[form.value.categoryId1,form.value.categoryId2,form.value.categoryId3]
    }
  })
}
const convertTree = (list) =>
    list.map(item => ({
      label: item.categoryName,
      value: item.id,
      children: item.children && item.children.length ? convertTree(item.children) : undefined
    }))

const categoryOptions = ref([])
const selectedCategories = ref([])

// 更新 form.categoryId1/2/3
const handleCategoryChange = (val) => {
  form.value.categoryId1 = val[0] || 0
  form.value.categoryId2 = val[1] || 0
  form.value.categoryId3 = val[2] || 0
}
const emit = defineEmits(['submitForm'])
// 提交
const submitForm = () => {
  form.value.agentId=form.value.agentId===null ||form.value.agentId.length===0 ?null:Number(form.value.agentId)
  templateupdate(form.value).then(()=>{
    emit('submitForm')
    ElMessage.success('操作成功')
  })
}

// 重置
const resetForm = () => {
  Object.assign(form.value, {
    templateTitle: '',
    categoryId1: 0,
    categoryId2: 0,
    categoryId3: 0,
    agentId: null,
    software: '',
    format: '',
    size: 0,
    pages: 0,
    proportion: '',
    limitation: '',
    copyrightNotice: '',
    viewOrder: 1,
    createTime: '',
  })
  selectedCategories.value = []
}
</script>

<style scoped>
.form-card {
  max-width: 1000px; 
}

.form-body {
  background-color: #f9fafc;
  padding: 20px;
  border-radius: 8px;
}
</style>
